﻿using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text.RegularExpressions;

namespace UserRegistration.Model.DP
{
    public class PhoneNumber
    {
        private readonly string number;
        public string Number => number;

        public PhoneNumber(string number)
        {
            if (number == null)
            {
                throw new ValidationException("number 不能为空");
            }
            else if (IsValid(number))
            {
                throw new ValidationException("number 格式错误");
            }
            this.number = number;
        }

        public string GetAreaCode()
        {
            for (int i = 0; i < number.Length; i++)
            {
                string prefix = number.Substring(0, i);
                if (IsAreaCode(prefix))
                {
                    return prefix;
                }
            }
            return null;
        }

        public static bool IsAreaCode(string prefix)
        {
            string[] areas = new string[] { "0571", "021", "010" };
            return areas.Contains(prefix);
        }

        public static bool IsValid(string phone)
        {
            string pattern = "^0[1-9]{2,3}-?\\d{8}$";
            return Regex.IsMatch(phone, pattern);
        }
    }
}